package cn.kgc.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.kgc.entity.Roles;
import cn.kgc.entity.RolesMenus;
import cn.kgc.mapper.RolesMapper;
import cn.kgc.service.RolesMenusService;
import cn.kgc.service.RolesService;
import cn.kgc.util.cache.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangyue
 * @version 1.0
 */
@Slf4j
@Service("rolesService")
@SuppressWarnings("all")
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {

    @Resource
    private RolesMenusService rolesMenusService;
    @Autowired
    private RedisUtil redisUtil;

    @Transactional
    @Override
    public boolean deleteRolesById(int id) {
        //根据角色id删除角色的信息
        removeById(id);
        //根据角色id删除角色菜单的信息
        LambdaQueryWrapper<RolesMenus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolesMenus::getRid, id);
        rolesMenusService.remove(wrapper);
        return true;
    }

    @Override
    @Transactional
    public boolean updateRolesMenus(Map<String, Object> map) {
        //1根据角色id删除角色已经拥有的菜单
        int roleId = MapUtil.getInt(map, "roleId");
        LambdaQueryWrapper<RolesMenus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolesMenus::getRid, roleId);
        rolesMenusService.remove(wrapper);
        //2添加角色菜单信息
        List<Integer> tempMenusId = (List<Integer>) map.get("menusId");

        List<RolesMenus> relesMenusList = tempMenusId.stream().map(menuId -> {
            RolesMenus rolesMenus = new RolesMenus();
            rolesMenus.setRid(roleId);
            rolesMenus.setMid(menuId);
            return rolesMenus;
        }).collect(Collectors.toList());
        //3删除系统中的所有按钮权限
        

        redisUtil.delete("system:authorities:*");
        return rolesMenusService.saveBatch(relesMenusList);
    }
}